<?php defined('SYSPATH') or die('No direct script access.');

    /** 结伴
     * Class Controller_Pc_Api_V2_Jieban
     */
    class Controller_Pc_Api_V2_Jieban extends Controller_Pc_Api_v2_Base
    {
        private $result;
        //应用类型id
        private $typeId = 11;


        public function before()
        {
            parent::before();
            // 检查会员信息
            $token       = Common::remove_xss($this->request_data->token);
            $check_token = Model_Api_V2_Pub::token_decode($token);
            if ($check_token['status']) {
                $this->mid = $check_token['mid'];
            }
            $this->result = array(
                'status' => true,//默认状态为成功
                'msg' => '操作成功',//默认的提示消息
                'data' => array()
            );
        }

        /**
         * 筛选时间
         */
        public function action_get_times()
        {
            $this->result['data'] = array(
                '全部时间',
                '今天',
                '1个月内',
                '1-3个月内',
                '3个月以上'
            );
            return $this->send_datagrams($this->client_info['id'], $this->result, $this->client_info['secret_key']);
        }

        /**
         * 获取结伴总人数
         */
        public function action_get_total()
        {
            $list      = DB::select('id', 'adultnum', 'childnum')->from('jieban')->where('status', 'in', array(1, 2))->and_where('ishidden', '=', 0)->execute()->as_array();
            $totalJoin = 0;
            foreach ($list as $v) {
                $joinnumArr = Model_Jieban_Join::get_join_number($v['id']);
                //总加入人数
                $totalJoin += intval($joinnumArr['adultnum']) + intval($joinnumArr['childnum']);
            }
            $this->result['data'] = Model_Jieban::get_jieban_total();
            return $this->send_datagrams($this->client_info['id'], $this->result, $this->client_info['secret_key']);
        }

        /**
         * 结伴筛选列表
         */
        public function action_get_list()
        {
            $page      = Common::remove_xss(intval($this->request_data->page));
            $destId    = Common::remove_xss(intval($this->request_data->dest_id));
            $timeIndex = Common::remove_xss(intval($this->request_data->time_index));
            $pagesize  = 30;
            $offset    = ($page - 1) * $pagesize;
            $nowday    = date('Y-m-d', time());
            $time      = strtotime($nowday);
            $w         = 'WHERE a.ishidden=0';
            if ($destId && $destId != '0') {
                $w .= " and find_in_set({$destId},a.kindlist) ";
            }

            switch ($timeIndex) {
                case 1: //今天
                    $w .= " and UNIX_TIMESTAMP(a.startdate) = $time ";
                    break;
                case 2: //1月以内
                    $w .= " and UNIX_TIMESTAMP(a.startdate) < ($time+30*24*60*60) ";
                    break;
                case 3: //1-3个月内
                    $w .= " and UNIX_TIMESTAMP(a.startdate) > ($time+30*24*60*60) and UNIX_TIMESTAMP(a.startdate) < ($time+90*24*60*60)";
                    break;
                case 4: //3个月以上
                    $w .= " and UNIX_TIMESTAMP(a.startdate) > ($time+90*24*60*60) ";
                    break;
                default:
                    $w .= " and UNIX_TIMESTAMP(a.startdate) >= $time ";
            }

            $sql = "SELECT a.id,a.kindlist,a.day,a.attrid,a.title,a.memo,a.shownum,a.startdate,a.memberid,a.vartime FROM `sline_jieban` AS a LEFT JOIN `sline_allorderlist` b ON (a.id=b.aid and b.typeid=11) ";
            $sql .= "{$w} AND a.status=1 AND a.day>0 ";
            $sql .= "ORDER BY IFNULL(b.displayorder,9999) ASC,a.addtime DESC ";
            $sql .= "LIMIT {$offset},{$pagesize}";
//        echo $sql;exit;
            $data = DB::query(1, $sql)->execute()->as_array();
//        var_dump($data);exit;
            foreach ($data as &$v) {
                //提取结伴图片
                $v['litpic']      = Model_Jieban::get_pic($v['memo']);
                $v['litpic']      = Model_Api_V2_System::uniapp_img($v['litpic'], 690, 345);
                $v['litpic']      = !empty($v['litpic']) ? $v['litpic'] : Model_Api_V2_System::uniapp_img(Common::nopic());
                $v['description'] = common::cutstr_html($v['memo'], 120);
                $startdate_string = explode('-', $v['startdate']);
                $v['startdate']   = $startdate_string[1] . '月' . $startdate_string[2] . '日';
                $memberInfo       = ORM::factory('member', $v['memberid'])->as_array();
                $v['memberName']  = $memberInfo['nickname'] ? $memberInfo['nickname'] : '游客';
                $v['memberName']  = substr($v['memberName'], 0, 12);
                $v['memberRank']  = isset($memberInfo['rank']) ? $memberInfo['rank'] : 0;
                $v['max_day']     = $v['vartime'] + $v['day'];
                $v['memberpic']   = $memberInfo['litpic'] ? $memberInfo['litpic'] : $GLOBALS['cfg_public_url'] . 'images/member_nopic.png';
                $joinnumArr       = Model_Jieban_Join::get_join_number($v['id']);
                $v['joinNum']     = intval($joinnumArr['adultnum']) + intval($joinnumArr['childnum']);
            }

            $this->result['data'] = $data;
            return $this->send_datagrams($this->client_info['id'], $this->result, $this->client_info['secret_key']);
        }

        /**
         * 获取结伴主题
         */
        public function action_get_theme()
        {
            $this->result['data'] = DB::select()->from('jieban_attr')->where('pid', '!=', 0)->and_where('isopen', '=', 1)->execute()->as_array();
            return $this->send_datagrams($this->client_info['id'], $this->result, $this->client_info['secret_key']);
        }

        /**
         * 提交结伴，编辑结伴
         * @return string
         */

        public function action_add_jieban()
        {
            if (!$this->mid) {
                $this->result['status'] = false;
                $this->result['msg']    = '请登录后重试';
                return $this->send_datagrams($this->client_info['id'], $this->result, $this->client_info['secret_key']);
            }
            //结伴id
            $id = Common::remove_xss($this->request_data->id);
            //目的地
            $kindlist = Common::remove_xss($this->request_data->kindlist);
            //标题
            $title = Common::remove_xss($this->request_data->title);
            //出发时间
            $startdate = Common::remove_xss($this->request_data->startdate);
            //出行时间偏差
            $vartime = Common::remove_xss(intval($this->request_data->vartime));
            //出行天数
            $day = Common::remove_xss(intval($this->request_data->day));
            //成人数
            $adultnum = intval($this->request_data->adultnum);
            //儿童数
            $childnum = intval($this->request_data->childnum);
            //主题
            $attrid = Common::remove_xss($this->request_data->attrid);
            //手机号码
            $mobile = Common::remove_xss($this->request_data->mobile);
            //结伴描述
            $memo = Common::remove_xss($this->request_data->memo);
            $data = array(
                'title' => $title,
                'startdate' => $startdate,
                'vartime' => $vartime,
                'day' => $day,
                'mobile' => $mobile,
                'adultnum' => $adultnum,
                'childnum' => $childnum,
                'memo' => $memo,
                'attrid' => $attrid,
                'kindlist' => $kindlist,
            );

            $validataion = Validation::factory($data);
            $validataion->rule('title', 'not_empty');
            $validataion->rule('startdate', 'not_empty');
            $validataion->rule('startdate', 'date');
            $validataion->rule('vartime', 'digit');
            $validataion->rule('day', 'digit');
            $validataion->rule('mobile', 'not_empty');
            $validataion->rule('mobile', 'phone');
            $validataion->rule('adultnum', 'digit');
            $validataion->rule('childnum', 'digit');
            if (!$validataion->check()) {
                $error = $validataion->errors();
                $keys  = array_keys($validataion->errors());
                if ($keys[0] == 'mobile') {
                    $this->result['status'] = false;
                    $this->result['msg']    = '手机号错误';
                } else {
                    $this->result['status'] = false;
                    $this->result['msg']    = __("error_{$keys[0]}_{$error[$keys[0]][0]}");
                }
                return $this->send_datagrams($this->client_info['id'], $this->result, $this->client_info['secret_key']);
            }
            if ($id) {
                $jieban = DB::select()->from('jieban')->where('id', '=', $id)->and_where('memberid', '=', $this->mid)->execute()->current();
                if ($jieban) {
                    if ($jieban['status'] > 0) {
                        $this->result['status'] = false;
                        $this->result['msg']    = '当前状态不允许修改';
                        return $this->send_datagrams($this->client_info['id'], $this->result, $this->client_info['secret_key']);
                    }
                } else {
                    $this->result['status'] = false;
                    $this->result['msg']    = '修改失败';
                    return $this->send_datagrams($this->client_info['id'], $this->result, $this->client_info['secret_key']);
                }
            }
            if ($id) {
                //修改
                DB::update('jieban')->set($data)->where('id', '=', $id)->execute();
            } else {
                list($insert_id, $total_rows) = DB::insert('jieban', array('kindlist', 'day', 'attrid', 'adultnum', 'childnum', 'vartime', 'startdate', 'addtime', 'memberid', 'title', 'mobile', 'memo'))
                    ->values(array($kindlist, $day, $attrid, $adultnum, $childnum, $vartime, $startdate, time(), $this->mid, $title, $mobile, $memo))
                    ->execute();
                if ($total_rows) {
                    $this->result['data'] = array('id' => $insert_id);
                } else {
                    $this->result['status'] = false;
                    $this->result['msg']    = '保存失败';
                }
            }

            return $this->send_datagrams($this->client_info['id'], $this->result, $this->client_info['secret_key']);
        }

        /**
         * 上传图片
         */
        public function action_uploads()
        {
            $img = Model_Api_V2_System::uniapp_img($this->request_data->litpic);
            if (!$img) {
                $this->result['status'] = false;
                $this->result['msg']    = '请上传图片';
                return $this->send_datagrams($this->client_info['id'], $this->result, $this->client_info['secret_key']);
            }
            $file = "/uploads/main/allimg/" . date('Ymd') . "/" . date('YmdHis') . rand(10000, 99999) . '.jpg';
            //判断目录是否存在 不存在就创建
            if (!is_dir(BASEPATH . "/uploads/main/allimg/" . date('Ymd') . "/")) {
                mkdir(BASEPATH . "/uploads/main/allimg/" . date('Ymd') . "/", 0777, true);
            }
            //写入图片
            if (strstr($img, ",")) {
                $image = explode(',', $img);
                $img   = $image[1];
            }
            if (file_put_contents(BASEPATH . $file, base64_decode($img))) {
                $this->result['msg']          = '上传成功';
                $this->result['data']['path'] = $file;
                $this->result['data']['img']  = Model_Api_V2_System::uniapp_img($file);
                return $this->send_datagrams($this->client_info['id'], $this->result, $this->client_info['secret_key']);
            } else {
                $this->result['status'] = false;
                $this->result['msg']    = '上传失败';
                return $this->send_datagrams($this->client_info['id'], $this->result, $this->client_info['secret_key']);
            }

        }

        /**
         * 结伴详情
         */
        public function action_get_detail()
        {
            $id = intval($this->request_data->id);
            //结伴详情
            $info = Model_Jieban::detail($id);

            if (empty($info)) {
                $this->result['status'] = false;
                $this->result['msg']    = '结伴已关闭';
                return $this->send_datagrams($this->client_info['id'], $this->result, $this->client_info['secret_key']);
            }

            //点击率加一
            Product::update_click_rate($id, $this->typeId);

            $info['memo'] = $info['memo'] ? $info['memo'] : $info['title'];
            //发布人
            $memberArr                = Model_Member::get_member_byid($info['memberid']);
            $info['member']['name']   = $memberArr['nickname'] ? $memberArr['nickname'] : $memberArr['nickname'];
            $info['member']['litpic'] = $memberArr['litpic'] ? $memberArr['litpic'] : Common::nopic();
            //目的地
            $info['kindnamelist'] = Model_Jieban::get_kindnamelist($info['kindlist']);
            //主题
            $info['attrlist'] = Model_Jieban_Attr::get_attr_list($info['attrid']);
            //加入人数
            $joinnumArr      = Model_Jieban_Join::get_join_number($info['id']);
            $info['joinNum'] = intval($joinnumArr['adultnum']) + intval($joinnumArr['childnum']);
            //封面图
            $info['litpic'] = Model_Api_V2_System::uniapp_img(Model_Jieban::get_pic($info['memo']));

            $this->result['data'] = $info;
            return $this->send_datagrams($this->client_info['id'], $this->result, $this->client_info['secret_key']);
        }

        /**
         * 加入结伴处理
         */
        public function action_join()
        {
            if (!$this->mid) {
                $this->result['status'] = false;
                $this->result['msg']    = '请登录后重试';
                return $this->send_datagrams($this->client_info['id'], $this->result, $this->client_info['secret_key']);
            }

            $id = intval($this->request_data->id);
            //联系人
            $linkman = Common::remove_xss($this->request_data->linkman);
            //电话
            $mobile = Common::remove_xss($this->request_data->mobile);
            //成人数
            $adultnum = Common::remove_xss(intval($this->request_data->adultnum));
            //儿童数
            $childnum = Common::remove_xss(intval($this->request_data->childnum));

            $jiban = DB::select()->from('jieban')->where('id', '=', $id)->execute()->current();
            if (!$jiban) {
                $this->result['status'] = false;
                $this->result['msg']    = '结伴已关闭';
                return $this->send_datagrams($this->client_info['id'], $this->result, $this->client_info['secret_key']);
            }
            if ($jiban['status'] == 0 || $jiban['status'] == 3) {
                $this->result['status'] = false;
                $this->result['msg']    = '该结伴已结束';
                return $this->send_datagrams($this->client_info['id'], $this->result, $this->client_info['secret_key']);
            }

            //检查用户重复加入结伴
            $join = Model_Jieban::repeat_join($this->mid, $id);
            if (!empty($join)) {
                $this->result['status'] = false;
                $this->result['msg']    = '您已加入该结伴';
                return $this->send_datagrams($this->client_info['id'], $this->result, $this->client_info['secret_key']);
            }

            $validataion = Validation::factory(array(
                'linkman' => $linkman,
                'mobile' => $mobile,
                'adultnum' => $adultnum,
                'childnum' => $childnum,
            ));
            $validataion->rule('linkman', 'not_empty');
            $validataion->rule('mobile', 'phone');
            $validataion->rule('adultnum', 'digit');
            $validataion->rule('childnum', 'digit');
            if (!$validataion->check()) {
                $error                  = $validataion->errors();
                $keys                   = array_keys($validataion->errors());
                $this->result['status'] = false;
                if ($keys[0] == 'mobile') {
                    $this->result['msg'] = '手机号错误';
                } elseif ($keys[0] == 'adultnum') {
                    $this->result['msg'] = '成人数错误';
                } elseif ($keys[0] == 'childnum') {
                    $this->result['msg'] = '儿童数错误';
                } else {
                    $this->result['msg'] = '联系人错误';
                }
                return $this->send_datagrams($this->client_info['id'], $this->result, $this->client_info['secret_key']);
            }
            list($insert_id, $total_rows) = DB::insert('jieban_join', array('jiebanid', 'linkman', 'mobile', 'memberid', 'adultnum', 'childnum', 'addtime'))
                ->values(array($id, $linkman, $mobile, $this->mid, $adultnum, $childnum, time()))
                ->execute();
            if ($total_rows) {
                //加入成功
                Model_Jieban::send_jieban_msg(2, $id, $this->mid); // 通知报名者
                Model_Jieban::send_jieban_msg(1, $id); // 通知发布者
                return $this->send_datagrams($this->client_info['id'], $this->result, $this->client_info['secret_key']);
            } else {
                $this->result['status'] = false;
                $this->result['msg']    = '加入失败';
                return $this->send_datagrams($this->client_info['id'], $this->result, $this->client_info['secret_key']);
            }
        }

        /**
         * 我的结伴列表
         */
        public function action_my_jieban()
        {
            $page                 = intval($this->request_data->page);
            $flag                 = intval($this->request_data->flag);
            $this->result['data'] = Model_Jieban::member_jieban_list($this->mid, $page, 10, $flag);
            return $this->send_datagrams($this->client_info['id'], $this->result, $this->client_info['secret_key']);
        }

        /**
         * 报名人数
         */
        public function action_people()
        {
            //结伴id
            $id                   = intval($this->request_data->id);
            $sql                  = "select * from sline_jieban_join WHERE jiebanid={$id}";
            $this->result['data'] = DB::query(1, $sql)->execute()->as_array();
            return $this->send_datagrams($this->client_info['id'], $this->result, $this->client_info['secret_key']);
        }

        /**
         * 关闭结伴
         * */
        public function action_close()
        {
            $id   = intval($this->request_data->id);
            $sql  = "update sline_jieban set status=3 where id=$id and status in (1,2)";
            $flag = DB::query(Database::UPDATE, $sql)->execute();
            if ($flag) {
                return $this->send_datagrams($this->client_info['id'], $this->result, $this->client_info['secret_key']);
            }
            $this->result['status'] = false;
            $this->result['msg']    = '关闭失败';
            return $this->send_datagrams($this->client_info['id'], $this->result, $this->client_info['secret_key']);
        }
    }